/*
 * MIT License
 *
 * Copyright (c) 2025 Mark·虎
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

package com.hsxxherp.key.support.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hsxxherp.key.common.util.TreeStructureUtil;
import com.hsxxherp.key.support.sys.entity.SysModule;
import com.hsxxherp.key.support.sys.mapper.SysModuleMapper;
import com.hsxxherp.key.support.sys.service.ISysModuleService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SysModuleServiceImpl extends ServiceImpl<SysModuleMapper, SysModule> implements ISysModuleService {
    @Override
    public List<SysModule> getSubModules(Long parentId) {
        QueryWrapper<SysModule> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pk_parent", parentId);
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public boolean save(SysModule entity) {
        Long parentId = entity.getPkParent();
        SysModule parentModule = null;
        List<SysModule> siblingModules = null;

        // 非根节点
        if (parentId != null) {
            parentModule = baseMapper.selectById(parentId);
            QueryWrapper<SysModule> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("pk_parent", parentId);
            siblingModules = baseMapper.selectList(queryWrapper);
        }
        try {
            entity.setInnercode(TreeStructureUtil.generateInnerCode(parentModule, (List<Object>) (List<?>) siblingModules));
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return super.save(entity);
    }

    @Override
    public void recalculateAllInnerCodes() {
        List<SysModule> allModules = baseMapper.selectList(null);
        try {
            List<SysModule> roots = TreeStructureUtil.convertToTree(allModules);
            if (!roots.isEmpty()) {
                SysModule root = roots.get(0);
                TreeStructureUtil.recalculateInnerCodes(root);
                for (SysModule module : flattenTree(root)) {
                    baseMapper.updateById(module);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private List<SysModule> flattenTree(SysModule root) {
        List<SysModule> result = new ArrayList<>();
        if (root != null) {
            result.add(root);
            if (root.getChildren() != null) {
                for (SysModule child : root.getChildren()) {
                    result.addAll(flattenTree(child));
                }
            }
        }
        return result;
    }
}